package com.soma.game.service.soma;

import com.google.common.collect.Maps;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import com.soma.game.model.SomaUser;
import com.soma.game.utils.SignUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: soma-game
 * @description: 和soma系统交互的服务
 * @author: hduprince
 * @create: 2018-07-18 14:44
 **/
@Service
public class SomaService {


    Logger logger = LoggerFactory.getLogger(SomaService.class);


    @Value("${soma.url}")
    private String baseUrl;

    private String PLAYER_PROFILE_URL = "/api/v1/minigame/getPlayerProfile";
    private String PLAYER_FRIEND_LIST_URL ="/api/v1/minigame/getPlayerFriendList";
    private String GROUP_PLAYER_LIST_URL ="/api/v1/minigame/getGroupPlayerList";

    private static final Configuration conf = Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .mappingProvider(new JacksonMappingProvider())
            .jsonProvider(new JacksonJsonProvider())
            .build();
    private TypeRef<List<Long>> typeRefLong = new TypeRef<List<Long>>(){};
    private TypeRef<List<SomaUser>> typeRefSomaUser = new TypeRef<List<SomaUser>>(){};


    /*{
      "code": 0,
      "msg": "",
      "obj": {
        "profiles": [
          {
            "avatar": "http://beta.soma.im/perm/580546028ae4d4eb06189743f69a93a.jpg",
            "id": 10000001,
            "name": "Chen"
          }
        ]
      },
      "success": true
    }
    */
    public SomaUser getUser(Long uid){
        Map<String, String> map = Maps.newHashMap();
        map.put("player_id", uid + "") ;
        SignUtil.getParma(map);

        try {
            String body = httpPost(PLAYER_PROFILE_URL, map);
            DocumentContext dc = JsonPath.using(conf).parse(body);
            boolean status = dc.read("$.success");
            if(status){
                List<SomaUser> result = dc.read("$.obj.profiles", typeRefSomaUser);
                return result.stream().findFirst().orElse(null);
            } else {
                logger.error("接口返回状态异常" + body);
            }
        } catch (IOException e) {
            logger.error("接口请求异常:" + e.getStackTrace());
        }
        return null;
    }


    public List<SomaUser> getUsers(String uid){
        Map<String, String> map = Maps.newHashMap();
        map.put("player_id", uid) ;
        SignUtil.getParma(map);

        try {
            String body = httpPost(PLAYER_PROFILE_URL, map);
            DocumentContext dc = JsonPath.using(conf).parse(body);
            boolean status = dc.read("$.success");
            if(status){
                List<SomaUser> result = dc.read("$.obj.profiles", typeRefSomaUser);
                return result;
            } else {
                logger.error("接口返回状态异常" + body);
            }
        } catch (IOException e) {
            logger.error("接口请求异常:" + e.getStackTrace());
        }
        return null;
    }


    /*
    {
      "code": 0,
      "msg": "",
      "obj": {
        "members": [
          10000004,
          10000001
        ]
      },
      "success": true
    }
    */
    public List<Long> getGroupUsers(Long sessionId) {

logger.info("sessionId : " + sessionId);
        Map<String, String> map = Maps.newHashMap();
        map.put("gid", sessionId + "");
Date parmaStart = new Date();
        SignUtil.getParma(map);
logger.info("parma time : {}", new Date().getTime() - parmaStart.getTime());

        try {
Date requestStart = new Date();
            String body = httpPost(GROUP_PLAYER_LIST_URL, map);
logger.info("request time : {}", new Date().getTime() - requestStart.getTime());
logger.info("body" + body);

            DocumentContext dc = JsonPath.using(conf).parse(body);
            boolean status = dc.read("$.success");
            if(status){
                List<Long> result = dc.read("$.obj.members", typeRefLong);
logger.info("result size : " + result.size());
                return result;
            } else {
                logger.error("接口返回状态异常" + body);
            }
        } catch (IOException e) {
            logger.error("接口请求异常:" + e.getStackTrace());
        }
        return null;
    }


    /*
    {
      "code": 0,
      "msg": "",
      "obj": {
        "friends": [
          10000002,
          10000003
        ]
      },
      "success": true
    }
     */
    public List<Long> getUserFriends(Long uid) {
logger.info("player_id" + uid);
        Map<String, String> map = Maps.newHashMap();
        map.put("player_id", uid + "") ;
Date parmaStart = new Date();
        SignUtil.getParma(map);
logger.info("parma time : {}", new Date().getTime() - parmaStart.getTime());

        try {
Date requestStart = new Date();
            String body = httpPost(PLAYER_FRIEND_LIST_URL, map);
logger.info("request time : {}", new Date().getTime() - requestStart.getTime());
logger.info("body" + body);
            DocumentContext dc = JsonPath.using(conf).parse(body);

            boolean status = dc.read("$.success");
            if(status){
                List<Long> result = dc.read("$.obj.friends", typeRefLong);
logger.info("result size : " + result.size());
                return result;
            } else {
                logger.error("接口返回状态异常" + body);
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("接口请求异常:" + e.getStackTrace());
        }
        return null;
    }


    public static void main(String[] args) {
        //new SomaService().getUser(10000001l);
        //new SomaService().getUsers("10000001,10000002");
        //new SomaService().getUserFriends(10000001l);
        //new SomaService().getGroupUsers("10000004", "0");
    }


    private String httpPost(String url, Map<String,String> map) throws IOException {
        //获取请求连接
        Connection con = Jsoup.connect(baseUrl + url);
        //遍历生成参数
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                //添加参数
                con.data(entry.getKey(), entry.getValue());
            }
        }
        Connection.Response doc = con.method(Connection.Method.POST).execute();
        return doc.body();
    }



}
